/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui;

import java.util.ArrayList;

import edu.bsu.android.gtv.apps.bconnected.data.PersonData;
import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.objects.Person;
import edu.bsu.android.gtv.apps.bconnected.util.Adapters;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.Constants;
import edu.bsu.android.gtv.apps.bconnected.util.DisclaimerHelper;
import edu.bsu.android.gtv.apps.bconnected.util.LoginHelper;
import edu.bsu.android.gtv.apps.bconnected.util.PersistentListFragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

/**
 * A simple {@link PersistentListFragment} that renders a list of connections.  The listfragment appears in the left hand column of the 
 * {@link ConnectionMultiPaneActivity} and when an item is selected, the connection info appears using the {@link ConnectionInfoFragment} in the 
 * right hand column.
 * @author Kyle Parker, University Computing Services
 */
public class ConnectionFragment extends PersistentListFragment {
    private static final String TAG = "ConnectionFragment";
	
    private Bundle mBundle = null;
	private OnConnectionListener mConnectionListener = null;
    private Adapters.PersonAdapter mAdapter;
    private ArrayList<Person> mConnections;
    private Activity mActivity;
    private BroadcastReceiver mReceiver;

    private String mBSUID;
    private String mLoginGuid;
    private String mPersonBSUID;
    private boolean mLogin;
    
    private int mPersonType = Constants.VALUE_PERSON_TYPE_STUDENT; 

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        mActivity = getActivity();
		this.mBundle = savedInstanceState;
		
		handleLogout();
		handleLogin();
        
    	if (!DisclaimerHelper.hasAcceptedDisclaimer(mActivity)) {
    		DisclaimerHelper.showDisclaimer(false, mActivity);
    	}
		
        AnalyticsUtils.getInstance(mActivity).trackPageView("/Connections");

        // NOTE: This differs from the other fragments - typically this is in the onCreate event
        // On rotation though, the view is not yet created and calling the load method (which references the views) after an 
        // orientation change causes a FC with the error "content view not created"
        // Placing the method call here eliminates that error and still draws the screen
        if (mLogin) {
        	loadConnections();
            
            // Set the list style
	    	Drawable selector = mActivity.getResources().getDrawable(R.drawable.left_pane_gradient_background); 
	    	//Drawable selector = mActivity.getResources().getDrawable(R.drawable.list_selector_background_default);
        	getListView().setBackgroundDrawable(selector);
            setListShown(false);
        }
    }
	
	@Override
	public void onResume() {
		super.onResume();
		
		restoreState(mBundle);
	}
    
    @Override 
    public void onDestroy() {
    	super.onResume();
    	mActivity.unregisterReceiver(mReceiver);
    }

    /** {@inheritDoc} */
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		if (mConnectionListener != null) {
	        // Get the person type of the connection based on the position in the list
	        Person person = (Person) getListView().getItemAtPosition(position);        
	        mPersonType = Integer.parseInt(person.getPersonType());
	        mPersonBSUID = person.getBSUID();
	        
			mConnectionListener.onConnectionSelected(mPersonBSUID, mPersonType);
		}
    }

    /**
     * Using a new thread, separate from the main activity, load the connections from the service handler
     */
    private void loadConnections() {
    	mConnections = new ArrayList<Person>();
    	mAdapter = new Adapters.PersonAdapter(mActivity, R.layout.list_item, mConnections, Constants.TARGET_CONNECTION);
        setListAdapter(this.mAdapter);
        
        Runnable load = new Runnable(){
            public void run() {
            	try {
        	        PersonData.initializeConnection(mBSUID, mLoginGuid, mActivity);
        	        
	                if (PersonData.getConnectionCount() > 0) {
	                	mConnections = PersonData.getConnections();
	                }
                    
            		mActivity.runOnUiThread(returnConnection);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread =  new Thread(null, load, "loadTerms");
        thread.start();
    }


    /**
     * Add each connection object from the service handler to the array adapter and set the visibility of the spinner to "gone"
     */
    private Runnable returnConnection = new Runnable(){
        public void run() {
        	if (mAdapter.getCount() > 0) {
        		mAdapter.clear();
        	}     
        	
            if (mConnections != null && mConnections.size() > 0){
                for(int i=0; i < mConnections.size(); i++) {
                	mAdapter.add(mConnections.get(i));
                }
                // If there are items, the list needs to enabled (or re-enabled in the event a blank list was loaded initially)
            	getListView().setEnabled(true);

                // Get the person type of the connection based on the position in the list
                Person person = (Person) getListView().getItemAtPosition(0);        
                mPersonType = Integer.parseInt(person.getPersonType());
                mPersonBSUID = person.getBSUID();
                      		
        		if (mConnectionListener != null) {
        			mConnectionListener.onConnectionSelected(mPersonBSUID, mPersonType);
        			getListView().setItemChecked(0, true);
        		}
            } else {
            	Person empty = new Person();
            	empty.setError(mActivity.getString(R.string.empty_connection));
            	mAdapter.add(empty);
            	
            	// If there are no items returned, disable the list selection
            	getListView().setEnabled(false);
            }
            
            mAdapter.notifyDataSetChanged();
            setListShown(true);
            getListView().setFocusable(true);
            getListView().requestFocus();
        }
    };
    
	public void setOnConnectionListener(OnConnectionListener listener) {
		this.mConnectionListener = listener;
	}
	
	public interface OnConnectionListener {
		void onConnectionSelected(String bsuID, int personType);
	}

    /**
     * In order to protect the activity from the back stack after a student logs out, remove the activity 
     * If the student hits the back button, this will take them to the Home activity
     */
    private void handleLogout() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_LOGOUT);
        mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
		        intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
		        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_LOGOUT));
		        
		        mActivity.startActivity(intent); 
			    mActivity.finish();
			}
		};
		
        mActivity.registerReceiver(mReceiver, intentFilter);
    }
    
    /**
     * Determine if the person has logged in and whether there is a person object in the database
     * Get the student's BSU ID for use throughout the application
     */
    private void handleLogin() {
    	Person person = LoginHelper.checkLogin(mActivity);
    	
    	if (person != null) {
    		mBSUID = person.getBSUID();
        	mLoginGuid = person.getLoginGuid();
    		mLogin = true;
    	} else {
	        Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
	        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_NOT_LOGGED_IN));
	        
	        mActivity.startActivity(intent); 
		    mActivity.finish();
		    
		    mLogin = false;
    	}    	
    }
}
